package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.enums.SettleStateEnum;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderExpress;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.CustomerOrderQuery;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.model.vo.order.OrderDataVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.EasyExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 后台客服订单相关API
 *
 * @author siashan
 * @since v1.0
 */
@RestController
@RequestMapping("customerOrder")
public class KefuOrderController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderOperationService orderOperationService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private IKefuOrderService kefuOrderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IOrderExpressService orderExpressService;
    @Autowired
    private IAfterSaleService afterSaleService;


    /**
     * 客服修改订单
     *
     * @param dto   修改参数
     * @return 修改结果
     */
    @PostMapping("chgOrder")
    public Result chgOrder(@Validated CustomerChgOrderDto dto) {
        SysAuth auth = AuthUtil.getSysExt();
        orderService.customerChgOrder(dto, auth.getUid());
        return ResultUtil.success();
    }

    /**
     * 修改订单备注
     *
     * @param dto  修改参数
     * @return 修改结果
     */
    @PostMapping("chgRemark")
    public Result chgRemark(@Validated @RequestBody ChgKefuRemarkDto dto) {
        SysAuth auth = AuthUtil.getSysExt();
        kefuOrderService.chgKefuRemark(dto,auth.getUid());
        return ResultUtil.success();
    }


    /**
     * 客服下单
     *
     * @param dto 下单参数
     * @return 下单结果
     */
    @PostMapping("place")
    public Result place(@RequestBody KefuPlaceOrderDto dto) {
        SysAuth auth = AuthUtil.getSysExt();
        return orderTradeService.kefuPlaceOrder(dto, auth);
    }


    /**
     * 断货订单列表
     *
     * @param query  查询参数
     * @return 订单列表
     */
    @GetMapping("selectOutOfStockList")
    public Result<IPage<OutOfStockCancelOrderVo>> outOfStock(CustomerOrderQuery query) {
        SysAuth auth = AuthUtil.getSysExt();
        return ResultUtil.success(orderService.selectOutOfStockList(initMpPage(), query, auth.getUid()));
    }

    /**
     * 断货订单列合计
     *
     * @param query  查询参数
     * @return 合计
     */
    @GetMapping("selectOutOfStockListTotal")
    public Result<StaticVo> outOfStockTotal(CustomerOrderQuery query) {
        return ResultUtil.success(orderService.selectOutOfStockListTotal(query));
    }

    /**
     * 售后订单列表
     *
     * @param query  查询参数
     * @return 订单列表
     */
    @GetMapping("afterSaleList")
    public Result<IPage<AfterSaleVo>> afterSaleList(CustomerOrderQuery query) {
        return ResultUtil.success(afterSaleService.loadAfterSaleList(initMpPage(), query));
    }

    /**
     * 售后订单列合计
     *
     * @apiNote 退货  afterSaleType = 1
     *          换货  afterSaleType = 2
     *
     * @param query  查询参数
     * @return 合计
     */
    @GetMapping("afterSaleTotal")
    public Result<StaticVo> afterSaleTotal(CustomerOrderQuery query) {
        return ResultUtil.success(afterSaleService.loadAfterSaleTotal(query));
    }

    /**
     * 未发货订单列表
     * @apiNote 退货  afterSaleType = 1
     *          换货  afterSaleType = 2
     * @param query  查询参数
     * @return 订单列表
     */
    @GetMapping("noShippedList")
    public Result<IPage<KefuAuditOrderVo>> noShippedList(CustomerOrderQuery query) {
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.AUDIT_SUCCESS.getValue());
        states.add(OrderStateEnum.SEALED.getValue());
        states.add(OrderStateEnum.PROBLEM.getValue());
        states.add(OrderStateEnum.WAIT_SHIP.getValue());
        query.setOrderStates(states);
        return ResultUtil.success(kefuOrderService.toAudit(initMpPage(), query));
    }

    /**
     * 未发货订单列合计
     *
     * @param query  查询参数
     * @return 合计
     */
    @GetMapping("noShippedTotal")
    public Result<StaticVo> noShippedTotal(CustomerOrderQuery query) {
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.AUDIT_SUCCESS.getValue());
        states.add(OrderStateEnum.SEALED.getValue());
        states.add(OrderStateEnum.PROBLEM.getValue());
        states.add(OrderStateEnum.WAIT_SHIP.getValue());
        query.setOrderStates(states);
        return ResultUtil.success(kefuOrderService.selectOrderListTotal(query));
    }

    /**
     * 订单列表
     *
     * @apiNote 订单列表, 正价订单列表，秒杀活动订单列表，代理商活动订单列表都使用该接口
     *               订单查看  orderType 不传
     *               正价订单  orderType 传 1
     *               代理商活动订单  orderType 传 2
     *               秒杀活动订单  orderType 传 3
     * @param query 查询参数
     * @return 订单列表
     */
    @GetMapping("list")
    public Result<IPage<KefuAuditOrderVo>> orderList(CustomerOrderQuery query) {
        return ResultUtil.success(kefuOrderService.selectOrderList(query, initMpPage()));
    }

    /**
     * 订单列表合计功能
     *
     * @param query  查询参数
     * @return 合计结果
     */
    @GetMapping("listTotal")
    public Result<StaticVo> orderListTotal(CustomerOrderQuery query) {
        return ResultUtil.success(kefuOrderService.selectOrderListTotal(query));
    }

    /**
     * 取消订单列表
     *
     * @param query  查询条件
     * @return 订单列表
     */
    @GetMapping("canceldList")
    public Result<IPage<KefuAuditOrderVo>> cancelList(CustomerOrderQuery query) {
        // 调整为货品取消状态
        query.setItemStatus(ProductStatusEnum.STATUS7);
        return ResultUtil.success(kefuOrderService.toAudit(initMpPage(), query));
    }

    /**
     * 取消订单列表 合计
     *
     * @param query  查询条件
     * @return 合计
     */
    @GetMapping("canceldListTotal")
    public Result<StaticVo> cancelListTotal(CustomerOrderQuery query) {
        //调整为货品取消状态
        query.setItemStatus(ProductStatusEnum.STATUS7);
        return ResultUtil.success(kefuOrderService.toAuditTotalAmount(query));
    }


    /**
     * 客服待审核订单
     *
     * @apiNote 待审核订单、正价待审核订单、代理商活动待审核订单、秒杀活动待审核订单 都使用该接口
     *          待审核订单  orderType 不传
     *          正价待审核订单  orderType 传 1
     *          理商活动待审核订单  orderType 传 2
     *          秒杀活动待审核订单  orderType 传 3
     * @param query 查询条件
     * @return 订单列表
     */
    @GetMapping("toAudit")
    public Result<OrderDataVo> toAudit(CustomerOrderQuery query) {
        query.setAuditDept(AuditDeptEnum.SERVICE_DEPT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        StaticVo totalAmount = kefuOrderService.toAuditTotalAmount(query);
        IPage<KefuAuditOrderVo> voIPage = kefuOrderService.toAudit(initMpPage(), query);
        return ResultUtil.success(new OrderDataVo(voIPage, totalAmount.getTotalAmount(),totalAmount.getTotalMarketAmount()));
    }

    /**
     * 客服已审核订单
     *
     * @param query  查询参数
     * @return
     */
    @GetMapping("hasAudit")
    public Result<OrderDataVo> hasAudit( CustomerOrderQuery query) {
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        StaticVo totalAmount = kefuOrderService.toAuditTotalAmount(query);
        IPage<KefuAuditOrderVo> voIPage = kefuOrderService.toAudit(initMpPage(), query);
        return ResultUtil.success(new OrderDataVo(voIPage, totalAmount.getTotalAmount(),totalAmount.getTotalMarketAmount()));
    }

    /**
     * 未绑定代理或者客服的订单--俗称野单
     *
     * @apiNote 目前只查正价的野单，秒杀的单子暂时无法界定野单【未认领订单】
     * @param query 查询参数
     * @return 订单列表
     */
    @GetMapping("noBindKefu")
    public Result noBindKefu(CustomerOrderQuery query) {
        query.setOrderType(OrderTypeEnum.NORMAL);
        query.setOrderFrom(OrderFromEnum.MEMBER);
        query.setIsPay(WhetherEnum.YES);
        StaticVo totalAmount = kefuOrderService.noBindKefuTotalAmount(query);
        IPage<KefuAuditOrderVo> orderVoIPage = kefuOrderService.noBindKefu(initMpPage(), query);
        BigDecimal total = totalAmount.getTotalAmount();
        return ResultUtil.success(new OrderDataVo(orderVoIPage, total,totalAmount.getTotalMarketAmount()));
    }

    /**
     * 未绑定代理的秒杀订单
     * @param query 查询条件
     * @return 订单列表
     */
    @GetMapping("noBindSeckill")
    public Result<OrderDataVo> noBindSeckill(CustomerOrderQuery query) {
        query.setOrderType(OrderTypeEnum.SECKILL);
        query.setIsPay(WhetherEnum.YES);
        query.setSeckillNobindFlag(WhetherEnum.YES);

//        StaticVo totalAmount = kefuOrderService.noBindKefuTotalAmount(query);
        StaticVo totalAmount = kefuOrderService.toAuditTotalAmount(query);
        IPage<KefuAuditOrderVo> orderVoIPage = kefuOrderService.toAudit(initMpPage(), query);
        BigDecimal total = totalAmount.getTotalAmount();
        return ResultUtil.success(new OrderDataVo(orderVoIPage, total,totalAmount.getTotalMarketAmount()));
    }

    /**
     * 秒杀已认领订单
     *
     * @param query 查询条件
     * @return 订单列表
     */
    @GetMapping("hasBindSeckill")
    public Result<OrderDataVo> hasBindSeckill(CustomerOrderQuery query) {
        query.setOrderType(OrderTypeEnum.SECKILL);
        query.setIsPay(WhetherEnum.YES);
        query.setIsClaim(OrderIsClaimEnum.HAS_CLAIM);

        StaticVo totalAmount = kefuOrderService.toAuditTotalAmount(query);
        IPage<KefuAuditOrderVo> orderVoIPage = kefuOrderService.toAudit(initMpPage(), query);
        BigDecimal total = totalAmount.getTotalAmount();
        return ResultUtil.success(new OrderDataVo(orderVoIPage, total,totalAmount.getTotalMarketAmount()));
    }

    /**
     * 已拒绝订单
     * @param  query 查询参数
     * @return 订单列表
     */
    @GetMapping("rejectList")
    public Result<IPage<KefuAuditOrderVo>> rejectList(CustomerOrderQuery query) {
        query.setOrderStatus(OrderStateEnum.REJECT);
        return ResultUtil.success(kefuOrderService.toAudit(initMpPage(), query));
    }

    /**
     * 已拒绝订单导出
     * @param  query 查询参数
     * @return 订单列表
     */
    @GetMapping("rejectListImport")
    public Result<IPage<KefuAuditOrderVo>> rejectListImport(CustomerOrderQuery query, HttpServletResponse response) {
        query.setOrderStatus(OrderStateEnum.REJECT);
        IPage<KefuAuditOrderVo> voIPage = kefuOrderService.toAudit(new Page(1,-1), query);
        List<KefuAuditOrderVo> records = voIPage.getRecords();
        try {
            String fileName="已拒绝订单列表";
            List<RejectOrderImportVo> rejectVos = Lists.newArrayList();
            RejectOrderImportVo importVo = null;
            for (KefuAuditOrderVo orderVo : records){
                importVo = new RejectOrderImportVo();
                BeanUtils.copyProperties(orderVo,importVo);
                importVo.setOrderTypeDesp(orderVo.getOrderType().getDesp());
                importVo.setAfterSale(0 == orderVo.getAfterSaleTag() ? "否" : "是");
                rejectVos.add(importVo);
            }
            EasyExcelUtil.writeExcel(response,RejectOrderImportVo.class,rejectVos,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultUtil.success(voIPage);
    }

    /**
     * 已拒绝订单统计
     *
     * @param query  查询参数
     * @return 合计结果
     */
    @GetMapping("rejectTotal")
    public Result<StaticVo> rejectTotal(CustomerOrderQuery query) {
        query.setOrderStatus(OrderStateEnum.REJECT);
        return ResultUtil.success(kefuOrderService.selectOrderListTotal(query));
    }


    /**
     * 未结算订单列表
     *
     * @param query 查询条件
     * @return  订单列表
     */
    @GetMapping("settleQuery")
    public Result<OrderDataVo> settleQuery(CustomerOrderQuery query) {
        query.setSettleState(SettleStateEnum.NOT_SETTLE);
        StaticVo totalAmount = kefuOrderService.toAuditTotalAmount(query);
        IPage<KefuAuditOrderVo> voIPage = kefuOrderService.toAudit(initMpPage(), query);
        return ResultUtil.success(new OrderDataVo(voIPage,totalAmount.getTotalAmount(),totalAmount.getTotalMarketAmount()));
    }

    /**
     * 客服下单订单列表
     *
     * @apiNote 目前只用于领导看板
     *
     * @param query 查询条件
     * @return  订单列表
     */
    @GetMapping("kefuOrder")
    public Result<IPage<KefuAuditOrderVo>> kefuOrder(CustomerOrderQuery query) {
        query.setOrderFrom(OrderFromEnum.CUSTOMER);
        IPage<KefuAuditOrderVo> voIPage = kefuOrderService.selectKefuOrderList(initMpPage(), query);
        return ResultUtil.success(voIPage);
    }



    /**
     * 秒杀活动绑定代理商
     *
     * @apiNote  是否有用？
     * @param id  订单id
     * @param agentId  代理id
     * @param remark 备注
     * @return 结果
     */
    @PostMapping("bind")
    @Deprecated
    public Result bind( Long id, Long agentId, String remark) {
        SysAuth auth = AuthUtil.getSysExt();
        orderService.bind(id, agentId, remark, auth.getUid());
        return ResultUtil.success();
    }

    /**
     * 订单审核
     *
     * @param dto  审核参数
     * @return  审核结果
     */
    @PostMapping("audit")
    @NoRepeatSubmit
    public Result audit(@Validated @RequestBody OrderAuditDto dto) {
        SysAuth auth = AuthUtil.getSysExt();
        orderOperationService.customerAudit(dto, auth);
        return ResultUtil.success();
    }

    /**
     * 客服批量审核
     *
     * @param ids  订单id，多个用英文逗号隔开
     * @return 审核结果
     */
    @PostMapping("auditBatch/{ids}")
    @NoRepeatSubmit
    public Result batchAudit( @PathVariable String ids) {
        SysAuth auth = AuthUtil.getSysExt();
        String[] arrayList = ids.split(",");
        List<OrderAuditDto> orderAuditDtoList = Lists.newArrayList();
        if (arrayList != null && arrayList.length > 0) {
            OrderAuditDto dto = null;
            for (String ss : arrayList) {
                dto = new OrderAuditDto();
                dto.setAuditState(AuditStateEnum.AGGREE);
                dto.setOrderId(Long.valueOf(ss));
                orderAuditDtoList.add(dto);
            }
        }
        if (CollUtil.isNotEmpty(orderAuditDtoList)) {
            for (OrderAuditDto dto : orderAuditDtoList) {
                orderOperationService.customerAudit(dto, auth);
            }
        }
        return ResultUtil.success();
    }

    /**
     * 批量拒绝
     *
     * @param ids 订单id，多个用英文逗号隔开
     * @return 结果
     */
    @PostMapping("auditRejectBatch/{ids}")
    @NoRepeatSubmit
    public Result auditReject( @PathVariable String ids) {
        SysAuth auth = AuthUtil.getSysExt();
        String[] arrayList = ids.split(",");
        List<OrderAuditDto> orderAuditDtoList = Lists.newArrayList();
        if (arrayList != null && arrayList.length > 0) {
            OrderAuditDto dto = null;
            for (String ss : arrayList) {
                dto = new OrderAuditDto();
                dto.setAuditState(AuditStateEnum.REJECT);
                dto.setOrderId(Long.valueOf(ss));
                orderAuditDtoList.add(dto);
            }
        }
        if (CollUtil.isNotEmpty(orderAuditDtoList)) {
            for (OrderAuditDto dto : orderAuditDtoList) {
                orderOperationService.customerAudit(dto, auth);
            }
        }
        return ResultUtil.success();
    }


    /**
     * 客服批量认领订单
     *
     * @param ids 订单id，多个用英文逗号隔开
     * @return 结果
     */
    @PostMapping("bindBatch/{ids}")
    public Result kufuBind(@PathVariable String ids) {
        kefuOrderService.bindBatch(ids);
        return ResultUtil.success();
    }


    /**
     * 修改订单属性
     *
     * @param paramDto  属性参数
     * @return 结果
     */
    @PostMapping("updateOrderParam")
    public Result updateOrderParam(@Validated @RequestBody OrderParamDto paramDto) {
        Long orderId = paramDto.getOrderId();
        Order order=orderService.getById(orderId);
       try{
           if(order.getSysTag().intValue()>=OrderSysTagEnum.YFH_TAG_109.getValue()){
               return ResultUtil.error("订单状态不对，不允许修改");
           }
       }catch (Exception e){
           e.printStackTrace();
       }
        if (null != paramDto.getHeight() || null != paramDto.getWeight()) {
            QueryWrapper<OrderGoods> wrapper = new QueryWrapper<OrderGoods>().eq("order_id", orderId);
            OrderGoods orderGoods = orderGoodsService.getOne(wrapper);
            orderGoods.setHeight(paramDto.getHeight());
            orderGoods.setWeight(paramDto.getWeight());
            orderGoodsService.updateById(orderGoods);
        }

        if (null != paramDto.getShipAddr()) {
            OrderExpress orderExpress = orderExpressService.findByOrderId(orderId);
            BeanUtils.copyProperties(paramDto.getShipAddr(), orderExpress);
            String phone=paramDto.getShipAddr().getContactPhone();
            if(ObjectUtil.isNotNull(phone)&&phone.contains("*")){
                orderExpress.setContactPhone(null);
            }
            orderExpressService.updateById(orderExpress);
        }
        return ResultUtil.success();
    }

    /**
     * 订单结算情况查询
     *
     * @param orderId  订单id
     * @return  状态
     */
    @PostMapping("settle/query/{orderId}")
    public Result settleQuery(@PathVariable Long orderId) {
        return orderOperationService.settleQuery(orderId);
    }

    /**
     * 订单重新发起结算
     *
     * @param orderId 订单id
     * @return 结果
     */
    @PostMapping("reSettle/{orderId}")
    public Result reSettle(@PathVariable Long orderId) {
        return orderOperationService.reSettle(orderId);
    }


    /**
     * 删除订单
     *
     * @param orderId  订单id
     * @return 删除结果
     */
    @PostMapping("del/{orderId}")
    public Result del(@PathVariable Long orderId) {
        Order order = orderService.getById(orderId);
        if (!OrderAuditStateEnum.AGENT_WAIT_AUDIT.getValue().equals(order.getAuditStatus())) {
            return ResultUtil.error("只有待审核订单才能删除");
        }
        if (OrderFromEnum.MEMBER.getValue().equals(order.getOrderFrom())) {
            return ResultUtil.error("会员订单禁止删除");
        }
        order.setIsDel(WhetherEnum.YES.getValue());
        orderService.updateById(order);
        return ResultUtil.success();
    }


    /**
     * 批量删除订单
     *
     * @param orderIds  订单id (多个id 英文逗号隔开)
     * @return 删除结果
     */
    @PostMapping("del/batch/{orderIds}")
    public Result delBatch(@PathVariable String orderIds) {
        String[] ids = orderIds.split(",");
        if (ids.length > 0) {
            for (String id : ids) {
                Long orderId = Long.parseLong(id);
                Order order = orderService.getById(orderId);
                if (!OrderAuditStateEnum.AGENT_WAIT_AUDIT.getValue().equals(order.getAuditStatus())) {
                    return ResultUtil.error("只有待审核订单才能删除");
                }
                if (OrderFromEnum.MEMBER.getValue().equals(order.getOrderFrom())) {
                    return ResultUtil.error("会员订单禁止删除");
                }
                order.setIsDel(WhetherEnum.YES.getValue());
                orderService.updateById(order);
            }
        }
        return ResultUtil.success();
    }

    /**
     * 换颜色尺码
     *
     * @param orderId  订单id
     * @param productId SKU id
     * @return 结果
     */
    @PostMapping("changeCode/{orderId}/{productId}")
    public Result changsCode( @PathVariable(value = "orderId") Long orderId, @PathVariable(value = "productId") Long productId) {
       OrderGoodsVo orderGoodsVo=orderGoodsService.findByOrderId(orderId);
       if(ObjectUtil.isNull(orderGoodsVo)){
           return  ResultUtil.error("订单信息查询为空");
       }
       if(orderGoodsVo.getProductId().equals(productId)){
           return  ResultUtil.error("颜色和尺码未更新，不需要提交");
       }
        orderService.changsCode(orderId, productId, false);
        return ResultUtil.success();
    }
}
